package youcaihuaoa.weetop.com.vm.login

import android.app.Application
import android.text.TextUtils
import androidx.databinding.ObservableField
import api.UserServiceFactory
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.StringUtils
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.configs.AppConstants
import com.robot.base.configs.PrefsManager
import com.robot.base.model.CustomListBean
import com.robot.base.model.LoginBean
import com.robot.base.model.UserInfoBean
import com.robot.base.util.ActivityUtils
import com.robot.base.util.ToastUtils
import com.robot.base.util.arouter.ARouterUtil
import com.umeng.socialize.bean.SHARE_MEDIA
import io.reactivex.Observable
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent
import me.goldze.mvvmhabit.http.BaseResponse
import youcaihuaoa.weetop.com.GlApp
import youcaihuaoa.weetop.com.R
import kotlin.math.log
import io.rong.imlib.RongIMClient

import youcaihuaoa.weetop.com.ui.login.LoginActivity

import io.rong.imkit.utils.RouteUtils

import io.rong.imkit.RongIM


class LoginViewModel(application: Application) : GLBaseViewModel(application) {
    val promptSelect = ObservableField(false)
    val closeSelect = ObservableField(false)
    val usernameField = ObservableField<String>()
    val passwordField = ObservableField<String>()
    val toLoginType = SingleLiveEvent<SHARE_MEDIA>()

    init {
        promptSelect.set(GlApp.checkProtocol)
    }

    val promptClick = BindingCommand<Any>(BindingAction {
        promptSelect.set(!promptSelect.get()!!)
        GlApp.checkProtocol = promptSelect.get() ?: false
    })

    val toQqClick = BindingCommand<Any>(BindingAction {
        if (checkPrompt())
            return@BindingAction
        doLogin()
//        toLoginType.postValue(SHARE_MEDIA.QQ)
    })

    private fun checkPrompt(): Boolean {
        if (promptSelect.get() == false) {
            ToastUtils.showShort(StringUtils.getString(R.string.app_error_4))
        }
        return promptSelect.get() == false
    }

    private fun doLogin() {
        val username = usernameField.get() ?: "test01"
        val password = passwordField.get() ?: "666666"

        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            ToastUtils.showShort("请输入用户名和密码!")
            return
        }

        val params = mapOf("account" to username, "password" to password)
        UserServiceFactory.login(params)
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<LoginBean>>(this) {
                override fun onNext(t: BaseResponse<LoginBean>) {
                    PrefsManager.saveUserLoginInfo(t.data)
                    getUser()
                }
            })
    }

    fun getUser() {
        UserServiceFactory.getUser()
            .subscribe(object :
                AbstractViewModelSubscriber<BaseResponse<UserInfoBean>>(this) {
                override fun onNext(t: BaseResponse<UserInfoBean>) {
                    PrefsManager.saveUserInfo(t.data)
                    loginByRongCloud()
                }
            })
    }

    private fun loginByRongCloud() {
        val token = PrefsManager.getUserLoginInfo().ry_token
        RongIM.connect(token, object : RongIMClient.ConnectCallback() {
            override fun onSuccess(userId: String) {
                // 登录成功，跳转到默认会话列表页。
                LogUtils.d("LoginViewModel----融云登录成功")
                ARouterUtil.goToActivity(AppConstants.Router.Main.A_MAIN)
            }

            override fun onError(connectionErrorCode: RongIMClient.ConnectionErrorCode) {
                LogUtils.d("LoginViewModel----融云登录失败")
            }

            override fun onDatabaseOpened(databaseOpenStatus: RongIMClient.DatabaseOpenStatus) {}
        })
    }

}